package com.kgc.kmall.kmallcartweb.controller;

import com.alibaba.fastjson.JSON;
import com.kgc.kmall.annotations.LoginRequired;
import com.kgc.kmall.bean.OmsCartItem;
import com.kgc.kmall.bean.PmsSkuInfo;
import com.kgc.kmall.service.CartService;
import com.kgc.kmall.service.SkuService;
import com.kgc.kmall.util.CookieUtil;

import org.apache.dubbo.config.annotation.Reference;
import org.junit.platform.commons.util.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.print.Book;
import java.math.BigDecimal;
import java.util.*;

@Controller
public class CartController {
    @Reference
    SkuService skuService;

    @Reference
    CartService cartService;


    @LoginRequired(value = false)
    @RequestMapping("/addToCart")
    public String addToCart(long skuId, Integer num, HttpServletRequest request, HttpServletResponse response){
        List<OmsCartItem> omsCartItems = new ArrayList<>();
        //把sku对象转换成购物车对象
        PmsSkuInfo pmsSkuInfo = skuService.selectBySkuId(skuId);
        //将商品信息封装成购物车信息
        OmsCartItem omsCartItem = new OmsCartItem();
        omsCartItem.setCreateDate(new Date());
        omsCartItem.setDeleteStatus(0);
        omsCartItem.setModifyDate(new Date());
        omsCartItem.setPrice(new BigDecimal(pmsSkuInfo.getPrice()));
        omsCartItem.setProductAttr("");
        omsCartItem.setProductBrand("");
        omsCartItem.setProductCategoryId(pmsSkuInfo.getCatalog3Id());
        omsCartItem.setProductId(pmsSkuInfo.getSpuId());
        omsCartItem.setProductName(pmsSkuInfo.getSkuName());
        omsCartItem.setProductPic(pmsSkuInfo.getSkuDefaultImg());
        omsCartItem.setProductSkuCode("11111111111");
        omsCartItem.setProductSkuId(skuId);
        omsCartItem.setQuantity(num);

        //判断是否登陆
        String memberId="";
        if (request.getAttribute("memberId")!=null){
            Integer id=(Integer) request.getAttribute("memberId");
            memberId=id+"";
        }
        if (StringUtils.isBlank(memberId)){
            //把商品信息保存的cookie
            // cookie里原有的购物车数据
            String cartListCookie = CookieUtil.getCookieValue(request, "cartListCookie", true);
            if (StringUtils.isBlank(cartListCookie)) {
                // cookie为空
                omsCartItems.add(omsCartItem);
            }else {
                // cookie不为空
                omsCartItems = JSON.parseArray(cartListCookie, OmsCartItem.class);

                if (omsCartItems!=null&&omsCartItems.size()>0){
                    // 判断添加的购物车数据在cookie中是否存在
                    boolean exist = if_cart_exist(omsCartItems, omsCartItem);
                    if (exist) {
                        // 之前添加过，更新购物车添加数量
                        for (OmsCartItem cartItem : omsCartItems) {
                            if (cartItem.getProductSkuId().equals(omsCartItem.getProductSkuId())) {
                              //
                                //修改数量
                                cartItem.setQuantity(cartItem.getQuantity()+num);
                                break;
                            }
                        }
                    }else {
                        // 之前没有添加，新增当前的购物车
                        omsCartItems.add(omsCartItem);
                    }
                }

            }
            System.out.println(JSON.toJSONString(omsCartItems));
            // 更新cookie
            CookieUtil.setCookie(request, response, "cartListCookie", JSON.toJSONString(omsCartItems), 60 * 60 * 72, true);
        }else {
            //把数据库保存到数据库
            OmsCartItem omsCartItemFromDb = cartService.ifCartExistByUser(Long.parseLong(memberId),skuId);
            if(omsCartItemFromDb==null){
                // 该用户没有添加过当前商品
                omsCartItem.setMemberId(Long.parseLong(memberId));
                omsCartItem.setMemberNickname("winder");
                cartService.addCart(omsCartItem);
            }else{
                // 该用户添加过当前商品
                Integer quantity = omsCartItemFromDb.getQuantity();
                quantity = quantity + num;
                omsCartItemFromDb.setQuantity(quantity);
                cartService.updateCart(omsCartItemFromDb);
            }

        }
        return "redirect:/success.html";
    }

    private boolean if_cart_exist(List<OmsCartItem> omsCartItems, OmsCartItem omsCartItem) {

        boolean b = false;

        for (OmsCartItem cartItem : omsCartItems) {
            Long productSkuId = cartItem.getProductSkuId();

            if (productSkuId.equals(omsCartItem.getProductSkuId())) {
                b = true;
                break;
            }
        }

        return b;
    }

    @LoginRequired(false)
    @RequestMapping("cartList")
    public String cartList(ModelMap modelMap, HttpServletRequest request, Model model){
        List<OmsCartItem> omsCartItems = new ArrayList<>();
        String memberId = "";
        if (request.getAttribute("memberId")!=null){
            Integer id=(Integer) request.getAttribute("memberId");
            memberId=id+"";
        }
        if(StringUtils.isBlank(memberId)){
            // 没有登录查询cookie
            String cartListCookie = CookieUtil.getCookieValue(request, "cartListCookie", true);
            if(StringUtils.isNotBlank(cartListCookie)){
                omsCartItems = JSON.parseArray(cartListCookie,OmsCartItem.class);
            }
        }else{
          // 已经登录查询db
            omsCartItems = cartService.cartList(memberId);
        }
        //总价
        BigDecimal totalAmount = getTotalAmount(omsCartItems);
        model.addAttribute("cartList",omsCartItems);
        model.addAttribute("totalAmount",totalAmount);
        return "cartList";
    }


    @LoginRequired(false)
   @RequestMapping("/checkCart")
   @ResponseBody
   public Map<String,Object> checkCart(String isChecked,Long skuId,HttpServletRequest request,HttpServletResponse response){
       Map<String,Object> map=new HashMap<>();
       String memberId = "";
        if (request.getAttribute("memberId")!=null){
            Integer id=(Integer) request.getAttribute("memberId");
            memberId=id+"";
        }
       if (StringUtils.isNotBlank(memberId)){
           // 调用服务，修改状态
           OmsCartItem omsCartItem = new OmsCartItem();
           omsCartItem.setMemberId(Long.parseLong(memberId));
           omsCartItem.setProductSkuId(skuId);
           omsCartItem.setIsChecked(isChecked);
           cartService.checkCart(omsCartItem);
           //计算总价
           List<OmsCartItem> omsCartItems = cartService.cartList(memberId);

           BigDecimal totalAmount =getTotalAmount(omsCartItems);
           map.put("totalAmount",totalAmount);
       }else{
           // 没有登录 查询cookie
           String cartListCookie = CookieUtil.getCookieValue(request, "cartListCookie", true);
           if(StringUtils.isNotBlank(cartListCookie)){
               List<OmsCartItem> omsCartItems = JSON.parseArray(cartListCookie,OmsCartItem.class);

               //修改
               for (OmsCartItem omsCartItem : omsCartItems) {
                   if (omsCartItem.getProductSkuId()==skuId){
                       omsCartItem.setIsChecked(isChecked);
                       break;
                   }
               }

               //保存cookie
               CookieUtil.setCookie(request, response, "cartListCookie", JSON.toJSONString(omsCartItems), 60 * 60 * 72, true);

               //计算总价
               BigDecimal totalAmount =getTotalAmount(omsCartItems);
               map.put("totalAmount",totalAmount);
           }

       }

       return map;
   }


   //计算总价
    public  BigDecimal getTotalAmount(List<OmsCartItem> omsCartItems) {
        BigDecimal totalMonye =new BigDecimal(0);
        for (OmsCartItem omsCartItem : omsCartItems) {
            BigDecimal price=omsCartItem.getPrice();
            Integer quantity=omsCartItem.getQuantity();

            omsCartItem.setTotalPrice(price.multiply(new BigDecimal(quantity)));
            if (omsCartItem.getIsChecked().equals("1"))
                totalMonye=totalMonye.add(omsCartItem.getTotalPrice());
        }

        return totalMonye;
    }

    //进行结算
    @LoginRequired(true)
    @RequestMapping("toTrade")
    public String toTrade() {

        return "toTrade";
    }


}
